<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace extend\kdniao;

use builder\helper\Http;
use builder\helper\T;
use common\helper\App;
use yii\base\BaseObject;

/**
 * 快递鸟-客户端
 * @auther clevstn
 * @since 2.0
 * @datetime 2023.11.18 14:38
 */
class Kdniao extends BaseObject
{
    // 用户ID，快递鸟提供，注意保管，不要泄漏
    const E_BUSINESS_ID = '8889999';
    // API key，快递鸟提供，注意保管，不要泄漏
    const API_KEY = '00000000-0000-0000-0000-000000000000';
    /**
     * @var string 错误信息
     */
    public $error;
    /**
     * @var mixed 业务结果
     */
    public $result;
    /**
     * @var BaseRequest
     */
    private $_request;

    /**
     * 接收成功应答
     * @return array
     */
    public static function success()
    {
        return [
            'EBusinessID' => self::E_BUSINESS_ID,
            'UpdateTime' => T::now(),
            'Success' => true,
            'Reason' => '',
        ];
    }

    /**
     * 接收失败应答
     * @param string $errMsg 失败原因
     * @return array
     */
    public static function failure($errMsg)
    {
        return [
            'EBusinessID' => self::E_BUSINESS_ID,
            'UpdateTime' => T::now(),
            'Success' => false,
            'Reason' => $errMsg,
        ];
    }

    /**
     * 数据签名
     * @param string $data 需要生成签名的数据
     * @return string
     */
    public static function generateSign($data)
    {
        return urlencode(
            base64_encode(
                md5($data . self::API_KEY)
            )
        );
    }

    /**
     * 数据验签
     * @param string $sign 签名
     * @param string $data 原数据
     * @return bool
     */
    public static function validateSign($sign, $data)
    {
        return !strcmp(
            $sign,
            base64_encode(
                md5($data . self::API_KEY)
            )
        );
    }

    /**
     * 设置快递鸟服务
     * @param BaseRequest $request
     * @return $this
     */
    public function setRequest(BaseRequest $request)
    {
        $this->_request = $request;
        return $this;
    }

    /**
     * 执行服务，返回执行状态
     * @param string $businessType 业务类型，如：order
     * @param int $businessID 业务ID，如：1502
     * @return bool
     */
    public function execute($businessType, $businessID)
    {
        $request = $this->_request;
        $execState = $this->sendRequest(
            $request->getRequestUrl(),
            $request->getRequestParams(),
            $request->getServiceName(),
            $businessType,
            $businessID
        );
        if ($execState) {
            $request->triggerResponseCallback($this);
            if ($this->hasError()) {
                $execState = false;
            }
        }

        return $execState;
    }

    /**
     * 是否有错误信息
     * @return bool
     */
    public function hasError()
    {
        return !empty($this->error);
    }

    /**
     * 发起请求
     * @param string $url 快递鸟服务URL
     * @param array $bodyParam 表单数据
     * @param string $serviceTitle 服务标题
     * @param string $businessType 业务类型
     * @param int $businessID 业务ID
     * @return bool
     */
    protected function sendRequest($url, $bodyParam, $serviceTitle, $businessType, $businessID)
    {
        $response = Http::req($url, 'post', 'urlencoded', $bodyParam);
        if ($response['code'] == 200) {
            $this->result = $response['result'];
            //日志:info
            App::logInfo('【快递鸟】' . $serviceTitle, [
                'BodyParams' => $bodyParam,
                'Response' => $response,
            ], $businessType, $businessID);
            return true;
        } else {
            $this->error = $response['result'];
            //日志:error
            App::logError('【快递鸟】' . $serviceTitle, [
                'BodyParams' => $bodyParam,
                'Response' => $response,
            ], $businessType, $businessID);
            return false;
        }
    }

    /**
     * @param array $config 实例化配置项
     * @return static
     */
    public static function createObject($config = [])
    {
        return new static($config);
    }
}